#include "PlaneBank.h"
#include <string>
#include "GameConfig.h"
#include "Config.h"
#include "pugixml.hpp"
#include "PlaneFactory.h"

using namespace pugi;

PlaneBank::PlaneBank(void)
{
	_listPlaneFactories = NULL;
	_listPlaneId = NULL;
}


PlaneBank::~PlaneBank(void)
{
	CC_SAFE_RELEASE(_listPlaneFactories);
	CC_SAFE_RELEASE(_listPlaneId);
}

PlaneBank* PlaneBank::sharedPlaneBank()
{
	if (!_instance)
		_instance = new PlaneBank();
	return _instance;
}

void PlaneBank::initBank()
{
	setPlaneFactories(CCDictionary::create());
	setPlaneIds(CCArray::create());

	// Stuff with xml
	std::string data = std::string(dynamic_cast<CCString*>(GameConfig::sharedGameConfig()->getConfigData()->objectForKey(CONFIG_PLANE))->getCString());
	xml_document doc;
	xml_parse_result result = doc.load(data.c_str());
	CCAssert(result.status == status_ok, "FAILD");
	

	xml_node node = doc.child("Root").child("Planes");
	
	for (xml_node i = node.first_child(); i; i = i.next_sibling("Plane"))
	{
		PlaneFactory* pFactory = PlaneFactory::create();
		pFactory->parseXml(i);
		_listPlaneFactories->setObject(pFactory, pFactory->getId()->getCString());
		_listPlaneId->addObject(pFactory->getId());
	}
}

void PlaneBank::clearBank()
{
	delete _instance;
	_instance = NULL;
}

PlaneFactory* PlaneBank::getPlaneFactoryById( char* id )
{
	return dynamic_cast<PlaneFactory*>(_listPlaneFactories->objectForKey(id));
}

CCString* PlaneBank::getIdByIndex( int i )
{
	if (i < 0)
		i = 0;
	else if (i >= _listPlaneId->count())
		i = _listPlaneId->count() - 1;

	return dynamic_cast<CCString*>(_listPlaneId->objectAtIndex(i));
}

PlaneBank* PlaneBank::_instance = NULL;
